package org.myhibernate.core.method;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.List;
import java.util.Map;

import org.myhibernate.core.method.CacheQuery;
import org.myhibernate.core.method.GenericMethod;
import org.myhibernate.db.DataHelper;

public class UpdateMethod<T> extends GenericMethod<T>
{
	private CacheQuery cacheQuery=null;
	public void init(Class cls, Connection connection) 
	{
		super.init(cls, connection);
		cacheQuery=new CacheQuery(connection, cls); 
	}
	@Override
	public void init(Class cl, DataHelper helper) {
		super.init(cl, helper);
		cacheQuery=new CacheQuery(cl, helper);
	}
	@Override 
	public void init(Class cl, Connection connection, DataHelper helper) {
		super.init(cl, connection, helper);
		cacheQuery=new CacheQuery(cl, connection, helper);
	}
	@Override
	public Object execute(Object obj, Map<String, Object> map) throws Exception 
	{
		boolean flag=false;
		PropertyDescriptor descriptor=null;
		// update to cache
		 descriptor= new PropertyDescriptor(getMapping().getId_Field(), getCl());
		 Method rM = descriptor.getReadMethod();
		 Object idValue=rM.invoke(obj);
		 //update to database
		try {
			List<String> fieldList=getMapping().getPropertyList();
			List<String> columnList=getMapping().getPropertyColList();
			
			String fieldName="";
			Object value=null;
			getBuffer().append("update "+getMapping().getTable()+" set ");
			for (int i = 0; i < fieldList.size(); i++) 
			{
				fieldName=fieldList.get(i);
				try {
					// descriptor= new PropertyDescriptor(fieldName, getCl());
					// rM = descriptor.getReadMethod();
					 rM=getCl().getDeclaredMethod(getMapping().getPropertyGetList().get(i));
					 value=rM.invoke(obj);
					 if (0==i)
					 {
						 getBuffer().append(columnList.get(i)+"="+getHandle().handle(value));
					} else {
						getBuffer().append(","+columnList.get(i)+"="+getHandle().handle(value));
					}
				} catch (Exception e) {
				}
			}//endfor
			// descriptor= new PropertyDescriptor(getMapping().getId_Field(), getCl());
			// rM = descriptor.getReadMethod();
			// value=rM.invoke(obj);
			getBuffer().append(" where "+getMapping().getId_Column()+"="+getHandle().handle(idValue));
			
			String sql=getSql();
			try {
				cacheQuery.executeSql(sql);
				flag=true;
			} catch (Exception e) 
			{
				e.printStackTrace();
				throw new RuntimeException(e.getMessage());
			}finally{
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}	
		return flag;
	}
	@Override
	public void close() {
		cacheQuery.close();
	}
}
